package com.meng.system.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meng.system.domain.dto.SysJobDTO;
import com.meng.system.mapper.job.JobMapper;
import com.meng.system.runnable.SchedulingRunnable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 项目启动时回调
 * 启动时加载库中已有并状态为正常运行的JOB
 *
 * 注：集群状态不建议启动去扫DB启动job
 * @author Mr.Still
 * @version 1.0.0
 * @date 2021-06-13 01:03
 **/
@Slf4j
@Service
public class SysJobRunner implements CommandLineRunner {

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) throws Exception {
        //拿到DB中状态为已启用的JOB
        QueryWrapper<SysJobDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("job_status",1);
        List<SysJobDTO> jobList = jobMapper.selectList(wrapper);
        if (jobList.size() == 0){
            log.info("=========>> 系统暂无已开启JOB....");
            return;
        }
        //开启job
        for (SysJobDTO job : jobList) {
            log.info("=========>> JOB 状态为=>"+job.getRunStatus()+"start");
            SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
            cronTaskRegistrar.addCronTask(task,job.getCronExpression());
            log.info("=========>> JOB:"+job.getMethodName()+"已启动....");
        }
    }
}
